package com.abl.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class DateKit {

    public static final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static String dateToStr(Date date, String formatStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        return sdf.format(date);
    }

    public static String nowDate() {
        return dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    public static String dateToStr(Date date) {
        return dateToStr(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date strToDate(String dateStr, String formatStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        Date pars = null;
        try {
            pars = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return pars;
    }

    public static Date strToDate(String dateStr) {
        return strToDate(dateStr, "yyyy-MM-dd HH:mm:ss");
    }


    /**
     * @param start yyyy-MM-dd 2019-02-01
     * @param end   yyyy-MM-dd 2019-02-03
     * @return start与end之间的所有日期 2019-02-01, 2019-02-02, 2019-02-03
     */
    public static List<String> betweenDates(String start, String end) {
        List<String> ret = new ArrayList<>();
        if (start.equals(end)) {
            ret.add(start);
            return ret;
        }
        final DateTimeFormatter formatDay = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate ldtStart = LocalDate.parse(start, formatDay);
        LocalDate ldtEnd = LocalDate.parse(end, formatDay);
        if (ldtEnd.isAfter(ldtStart)) {
            ret.add(start.substring(0, 10));
            ret.add(end.substring(0, 10));
            while (ldtStart.isBefore(ldtEnd)) {
                ldtStart = ldtStart.plusDays(1);
                ret.add(ldtStart.format(formatDay));
            }
        }
        return ret;
    }

    public static List<String> monthDays() {
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int maxDay = aCalendar.getActualMaximum(Calendar.DATE);
        String ym = dateToStr(new Date(), "yyyy-MM-");
        String ymdStart = ym + "01";
        String ymdEnd = ym + maxDay;
        return betweenDates(ymdStart, ymdEnd);
    }


}
